/**
 * Copyright (c) 2015-2019, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.column/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.module.column;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.module.column.validator.ColumnValidator;
import cn.hg.jfsa.manage.service.ColumnService;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.Column;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.web.theme.ThemeManager;

/**
 * @author Golly
 */
public class ColumnController extends BaseController {

	/**
	 * 机构服务
	 */
	@Inject
	private ColumnService columnService;

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		Integer parentId = this.getParaToInt("parentId", 0);
		Column parent = new Column().setParentId(0).put("parent_name", "").setSortNum(0);

		if (parentId > 0) {
			parent = Column.DAO.findById(parentId);
		}

		// 创建新记录
		this.setAttr("column", new Column().setParentId(parentId).put("parent_name", parent.getName()));
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("column")
	public void ajaxDel () {
		// 通过页面传入的ID查找到记录
		Column bean = Column.DAO.findById(this.getParaToInt("id"));

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {
				ColumnController.this.columnService.del(bean, true);
				// 更新父对象的子对象ID列表
				ColumnController.this.columnService.updateColumnChildredIds(Column.DAO.findById(bean.getParentId()));
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式获取机构树
	 */
	@SuppressWarnings ("unchecked")
	@Before (POST.class)
	public void ajaxGetColumnTree () {
		this.renderJson(this.columnService.getTree(Kv.by("theme", ThemeManager.me().getCurrentTheme().getId())));
	}

	/**
	 * Ajax方式获取机构树
	 */
	@Before (POST.class)
	public void ajaxGetOrgTree () {
		this.renderJson(this.columnService.getTree(new HashMap<String, Object>()));
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before ({
		ColumnValidator.class, EvictInterceptor.class
	})
	@CacheName ("column")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		Column bean = this.getBean(Column.class, "column");

		if (bean.getParentId().equals(bean.getId())) {
			this.renderAjaxFailed("1", "上级机构不能是自己！");
			return;
		}

		JfsaAdmin currAdmin = JfsaThreadLocal.getAdmin();
		Column parent = Column.DAO.findById(bean.getParentId());
		// 这里引用事务处理是为了方便Ajax模式处理
		boolean successed = Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 初始化数据
					bean.setCreatorId(currAdmin.getId())
						.setCreatedTime(new Date())
						.setEditorId(currAdmin.getId())
						.setEditedTime(new Date())
						.setTheme(ThemeManager.me().getCurrentTheme().getId())
						.setPathIds(parent == null ? ""
							: parent.getPathIds() + (parent.getPathIds().length() > 0 ? "," : "")
								+ parent.getId())
						.setLayerNum(null == parent ? 0 : parent.getLayerNum() + 1);
					// 新建记录
					bean.save();
				} else {
					// 更新记录
					bean.setEditorId(currAdmin.getId()).setEditedTime(new Date()).update();
				}

				// 更新父对象的子对象ID列表
				ColumnController.this.columnService.updateColumnChildredIds(parent);
				return true;
			}

		});

		// 返回Ajax成功
		if (successed) {
			this.renderAjaxSuccessed();
		} else {
			this.renderAjaxFailed("1", "操作失败！");
		}

	}

	/**
	 * Ajax方式查询
	 */
	// @Before(CacheInterceptor.class)
	// @CacheName("column")
	public void ajaxSearch () {
		// 建立查询键值对
		Kv para = Kv.by("status", this.getPara("status"))
			.set("theme", ThemeManager.me().getCurrentTheme().getId());
		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findColumn", para);
		List<Column> list = Column.DAO.find(sqlPara);
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(list));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		Column bean = Column.DAO.findById(this.getParaToInt("id"));
		Column parent = Column.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getParentName());
		}

		// 查询目标记录
		this.setAttr("column", bean);
	}

	/**
	 * 跳转到列表页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("column")
	@Override
	public void index () {}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("column")
	public void view () {
		Column bean = Column.DAO.findById(this.getParaToInt("id"));

		if (bean == null) {
			this.render("../record_not_exist.html");
			return;
		}

		Column parent = Column.DAO.findById(bean.getParentId());

		if (parent != null) {
			bean.put("parent_name", parent.getParentName());
		}

		this.setAttr("column", bean);
	}

}
